package com.letwal.cmcvnd.utils.update;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.letwal.cmcvnd.ProjectApplication;

import java.io.File;
import java.io.FileNotFoundException;

public class ZHIInstallAPK {

    public static boolean isInstalling = false;

    public static boolean installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            return false;
        }
        try {
            File oldFile = new File(apkPath);
            if (!oldFile.exists()) {
                return false;
            }
            if (isInstalling) {
                isInstalling = false;
                return false;
            }
            isInstalling = true;
            ProjectApplication.instance.startActivity(getInstallApkIntent(apkPath));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Intent getInstallApkIntent(String apkPath) {
        try {
            Log.d("getInstallApkIntent", "apkPath: " + apkPath);
            File apkFile = new File(apkPath);
            if (!apkFile.exists()) {
                throw new FileNotFoundException("Apk file does not exist!");
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                apkUri = FileProvider.getUriForFile(ProjectApplication.instance, ProjectApplication.instance.getPackageName() + ".file_provider", apkFile);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                apkUri = Uri.fromFile(apkFile);
            }
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            return intent;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
